//添加账户
import React,{Component} from 'react'
import ReactDOM from 'react-dom'
import {Modal,Form,Input,InputNumber,Row,Col,Upload,Icon,Button} from 'antd';
import $ from 'jquery'
import './AddUser.css'
import * as tools from '../../tools/tools';
import NumberInput from '../NumberInput/NumberInput'
import PayMethod from '../PayMethod/PayMethod'   //付费方式页面

const FormItem = Form.Item;


class AddUser extends Component{
    constructor(props){
        super(props);
        this.filearr = [];
        this.uploadadress=[];
        this.state={
            detailvisible:false,
            visible:false,
            previewVisible: false,
            previewImage: '',
            fileList: [],
            timedata:null,
            methoddata:null,
            value1:0,
            uploadImage:null,
            
        }
    }

    componentWillMount(){                     //省市二级联动
        $.ajax({
            type:'Post',
            url: tools.apiUrl +'common/regions',
            data:{
                token: localStorage.token,
            },
            success:(res)=>{
                this.setState({
                    timedata: res.result
                })
            },
        })
    }
 

    handleSubmit = (e) => {         //表单提交函数（添加用户）
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
            Object.assign(values,this.state.methoddata)
            values.is_refillings = 'no';
            values.agency_account_log_id = 0;
            delete values.photoshop;
            if(this.props.type === 1){  //企业
                values.service_charge = 0;
                values.parent_mobile = 0;
                values.province_id = this.refs.Option1.value;
                values.city_id = this.refs.Option2.value;
            }
            values.service_charge /=100;
            values.agency_type = this.props.type == 1?1:2;
            values.token = localStorage.token,
            values.contract_picture = this.uploadadress;
            // console.log(values)
            if (!err) {
                tools.loginView(this).then(
                $.ajax({
                    type:'Post',
                    url: tools.apiUrl+'agency/agency_enter',
                    data:values,
                    success:(res)=>{
                        this.props.onCancel();
                        this.props.form.resetFields();
                    },
                })
            )
            }
        })
        
    }

    checkPassword=(rule, value, callback) =>{     //密码相同==>传值必须是(rule,value,callback)其中callback必须写里面内容
        const form = this.props.form;               //表单里面对输入框等的限制函数
        if (value && value !== form.getFieldValue('password')) {
            callback('两次密码输入不一致！');
        } else if(form.getFieldValue('password')!=null && value == null || value == ''){
            callback("请重复密码!");
        }else{
            callback()
        }
    }

    rate=(rule,value,callback)=>{           //费率限制
        if(value <0.26){
            callback(" ")
        }else if(value>0.3){
            callback(" ")
        }else{
            callback()
        }
    }

    handlesmallCancel = () => {             // modal取消函数 image
        this.setState({ 
            previewVisible: false 
        })
    } 
    

    handlePreview = (file) => {        // 点击图片打开大图函数
        this.setState({
          previewImage: file.url || file.thumbUrl,
          previewVisible: true,
        });
    }

    handleChange = ({ fileList }) => {      // 上传文件改变时的状态，有点麻烦，看api  
        this.setState({
            fileList
        })
    }  
   
    option1Value=()=>{   //省获取到市的id
        var s = ReactDOM.findDOMNode(this.refs.Option1);
        return s ? s.value : 0;
    }
    option1ChangeValue =()=>{   //保存市的id
        let value12 = this.option1Value();
        this.setState({
            value1: value12-1
        });

    }


    cityname=(obj)=>{      //由省获取市的所有option
        if(this.state.timedata){
            return this.state.timedata[obj].child.map((child)=>{
                return (<option key={child.id} value={child.id}>{child.name}</option>);
            });
        
        }
    }

    detailModal=()=>{    //modal打开
        this.setState({
          detailvisible:true
        })
    }
   
    methoddata=(obj)=>{  //子页面传过来的数据。需要加到handleSubmit函数里面去
        this.setState({
            methoddata:obj
        })
        
    }
    normFile = (e) => {
        // console.log('Upload event:', e);
        if (Array.isArray(e)) {
          return e;
        }
        return e && e.fileList;
      }
   
    beforeUpload=()=>{       //从后台请求上传到oss需要的数据
        $.ajax({
            type:'Post',
            url: tools.apiUrl+'common/oss_policy',
            async: false,
            data:{
                token: localStorage.token,
            },
            success: (res)=>{
                this.setState({
                    uploadImage:res.result
                })
            }
        })
    }

    customRequest=(info)=>{            //上传图片至oss，但是有bug用action能显示缩略图，用customRequest自定义上传缩略图不显示
        
        const uploadImage = this.state.uploadImage;
        let key = Date.now().toString(36)+Math.random().toString(36).substr(3,3)
        var obj = new FormData();
        obj.append( "key" , uploadImage.dir+key+'.'+info.file.type.substr(info.file.type.indexOf('/')+1))   
        obj.append( "policy", uploadImage.policy)
        obj.append( "OSSAccessKeyId", uploadImage.accessid)
        obj.append( "success_action_status" , '200')
        obj.append( "callback",uploadImage.callback)
        obj.append( "expire",parseInt(uploadImage.expire))
        obj.append( "signature",uploadImage.signature)
        obj.append( "file",info.file)

        this.nativeAjax({
            data:obj,
            url:uploadImage.host,
            success:(res)=>{
                // console.log(res)
                this.uploadadress.push(res.result)   //数组随机名字
            }
        })
        }
        nativeAjax=({type = 'POST',data = {},success = null,url = ''})=> {   //简易ajax原生
            var oReq = new XMLHttpRequest();
            oReq.open(type, url);
            oReq.send(data);
            
            oReq.onreadystatechange = function () {
                if (oReq.readyState === 4 && oReq.status === 200) {
                var res = JSON.parse(oReq.response);
                    if (success) {
                        success(res)
                    }
                }
            }
    }
    onChange = (value) => {
        this.setState({ value });
    }
    detailcancel=()=>{
        this.setState({
            detailvisible:false
        })
    }
    addusercancel=()=>{
        this.props.form.resetFields();
        this.props.onCancel();
    }

    render(){
        const { getFieldDecorator } = this.props.form;
        const { previewVisible, previewImage, fileList } = this.state;
        const uploadButton = (
            <div>
                <Icon type="plus" />
                <div className="ant-upload-text">Upload</div>
            </div>
        );
        let cityname = this.cityname(this.state.value1);
        return(
            <Modal title="添加账号" className="modal_box"
                visible={this.props.show}
                maskClosable={false}
                onOk={this.handleSubmit}
                onCancel={this.addusercancel}
                bodyStyle={{height:'700px',overflow: 'auto'}}
                >
                
                <Form layout="vertical" onSubmit={this.handleSubmit}>
                    <div>
                        <div className="modal_add_title"><span>添加账号</span></div>
                        <Row>
                            <Col span={13}>
                                <FormItem label="名称" hasFeedback={true} >                                              {/* rules是控制其内容，required是否显示图标 message输入错误提示  min max最小最大输入字段 */}
                                    {getFieldDecorator('name', { 
                                        rules: [{ required: true, message: '请输入20字以内的名称!',min:1,max:20 }]})(
                                        <Input placeholder="请输入新名称" />    
                                    )}
                                </FormItem>
                            </Col>
                            <Col span={13}>
                            <FormItem label="电话" hasFeedback="true" >
                                {getFieldDecorator('mobile', { 
                                    rules: [{required:true,message: '请输入11位手机号码!',pattern:"^[1][3,4,5,7,8][0-9]{9}$" }]})(          //pattern 正则判断
                                    <Input placeholder="请输入手机号"  />    
                                )}
                            </FormItem>
                            </Col>
                            <Col span={13}>
                            <FormItem label="密码" hasFeedback="true" >
                                {getFieldDecorator('password', { 
                                    rules: [{required: true,message: '请输入6-20位字符、数字!',min:6,max:20 }]})(
                                    <Input placeholder="请输入新密码"  type="password"/>    
                                )}
                            </FormItem>
                            </Col>
                            <Col span={13}>
                            <FormItem label="重复密码" hasFeedback="true" >
                                {getFieldDecorator('password1', { 
                                    rules: [{required: true,validator:this.checkPassword,min:6,max:20 }]})(                                       //validator  自己写js去控制
                                    <Input placeholder="请输入新密码"  type="password"/>    
                                )}
                            </FormItem>
                            </Col>
                        </Row>
                    </div>
                    <div>
                        <div className="modal_add_title"><span>银行信息</span></div>
                        <Row>
                            <Col span={13}>
                                <FormItem label="开卡人姓名" hasFeedback="true" >
                                    {getFieldDecorator('cash_name',{
                                        rules:[{type: "string",required:true,message:'请输入开卡人姓名'}]
                                    })(
                                        <Input placeholder="请输入开卡人姓名" />    
                                    )}
                                </FormItem>
                            </Col>
                            <Col span={13}>
                            {/* <InputNumber  placeholder="请输入银行账号"  />     */}
                            <FormItem label="银行账户" hasFeedback="true" >
                                {getFieldDecorator('cash_card',{
                                    rules:[{required:true,message:'请输入银行账号', }]
                                })(
                                    
                                    <NumberInput placeholder="请输入银行账户"/>
                                )}
                            </FormItem>
                            </Col>
                            <Col span={13}>
                            <FormItem label="开卡银行" hasFeedback="true" >
                                {getFieldDecorator('cash_bank',{
                                    rules:[{type: "string",required:true,message:'请输入开卡银行!'}]
                                })(
                                    <Input placeholder="请输入开卡银行"  />    
                                )}
                            </FormItem>
                            </Col>
                            <Col span={13}>
                            <FormItem label="所在支行" hasFeedback="true" >
                                {getFieldDecorator('cash_branch_bank',{
                                    rules:[{required:true,message:'请输入支行名称!'}]
                                })(
                                    <Input placeholder="请输入具体支行名称" />    
                                )}
                            </FormItem>
                            </Col>
                            <Col span={13}>
                            <FormItem label="银联" >
                                {getFieldDecorator('bank_node')(
                                    <NumberInput  placeholder="请输入银联账户"/>
                                )}
                            </FormItem>
                            </Col>
                        </Row>
                    </div>
                    <div>
                        <div className="modal_add_title"><span>签约信息</span></div>
                        <Row>
                            <Col span={13}>
                                {this.props.type == 18? <FormItem label="签约人" hasFeedback="true" >
                                    {getFieldDecorator('signatory',{
                                    rules:[{required:true,message:'请输入签约人!'}]
                                })(
                                        <Input placeholder="请输入签约人姓名" />    
                                    )}
                                </FormItem> : <FormItem label="城市服务商账号" hasFeedback="true">
                                    {getFieldDecorator('parent_mobile',{
                                        rules:[{required:true,message:'请输入账号!'}]
                                    })(
                                            <Input placeholder="请输入城市服务商账号" />    
                                        )}
                                    </FormItem>}
                                
                               {/*省市可以存本地，减少请求---未改动--现未改动*/}
                            </Col>
                            <Col span={13}>
                            {this.props.type == 18? <FormItem label="代理区域" >            
                                <select placeholder="请输入省份" onChange={this.option1ChangeValue} ref="Option1" className="modal_add_select">                                  
                                    {this.state.timedata ? this.state.timedata.map((item)=>{
                                            return(
                                                <option key={item.id} value={item.id}>{item.name}</option>
                                            )
                                        }):false}
                                </select>
                                <select placeholder="请输入市区"  ref="Option2" className="modal_add_select">
                                    {cityname}                            
                                </select>    
                            </FormItem>:<FormItem label="签约费率" hasFeedback>
                                    {getFieldDecorator('service_charge',{
                                        rules:[{required:true,validator:this.rate}]
                                    })(
                                            <NumberInput placeholder="费率(0.26~0.3)" />    
                                        )}%
                                    </FormItem>}
                           
                            </Col>
                            {this.props.type ==18 ? false:<Col span={13}>
                            <FormItem label="签约人" hasFeedback="true" >
                                    {getFieldDecorator('signatory',{
                                    rules:[{required:true,message:'请输入签约人!'}]
                                })(
                                        <Input placeholder="请输入签约人姓名" />    
                                    )}
                                </FormItem>
                                </Col>}
                            <Col span={13}>
                            <FormItem label="付费方式" hasFeedback="true" >
                                {this.state.methoddata ?                  
                                        <Button type="primary" onClick={this.detailModal}>已填写</Button>
                                     :                                        
                                        <Button type="danger" onClick={this.detailModal}>未填写</Button> 

                                }
                               
                            </FormItem>
                            </Col>
                            <Col span={13}>
                            <FormItem label="合同编号" hasFeedback="true" >
                                {getFieldDecorator('contract_no',{
                                    rules:[{required:true,message:'请输入合同编号!'}]
                                })(
                                    <Input placeholder="请输入合同编号" />    
                                )}
                            </FormItem>
                            </Col>
                            <Col span={24}>
                                <FormItem >
                                    {getFieldDecorator(('photoshop'),{
                                     
                                        getValueFromEvent: this.normFile,
                                    })(
                                        
                                        <Upload                                                         //上传图片后页面未显示bug---未更改（可能需自己重新封装）
                                            className="modal_upload"
                                            customRequest={this.customRequest}
                                            listType="picture-card"
                                            fileList={fileList}
                                            onPreview={this.handlePreview}
                                            onChange={this.handleChange}
                                            beforeUpload={this.beforeUpload}
                                        >
                                            {fileList.length >= 3 ? null : uploadButton}
                                      </Upload>
                                    )}
                                
                                    <Modal visible={previewVisible} footer={null} onCancel={this.handlesmallCancel} maskClosable={false}>    
                                        <img alt="example" style={{ width: '100%' }} src={previewImage} />
                                    </Modal>
                                </FormItem>

                            </Col>
                        </Row>
                    </div>
                    <div>
                        <div className="modal_add_title"><span>备注</span></div>
                        <FormItem >
                            {getFieldDecorator('settlement_remark',{
                                    rules:[{required:true,message:'请输入备注!'}]
                                })(
                                <textarea cols="100" rows="5" placeholder="请输入备注，最多250字"  maxLength="250" style={{resize:'none'}}></textarea>
                            )}
                           
                        </FormItem>
                    </div>
                </Form>
                <PayMethod show={this.state.detailvisible} onCancel={this.detailcancel} methoddata={this.methoddata}></PayMethod>
            </Modal>
        )
    }
}
const newAddUser  = Form.create()(AddUser);
export default newAddUser
